package com.pride1952.myoptimusx3;

import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link RingFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link RingFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RingFragment extends Fragment implements View.OnClickListener{
    private final String TAG = "RingFragMent";
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final int BLUETOOTH_ACITON=0;
    private final int BLUETOOTH_ACTION_DELAY=3000;
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    private View mView;

    private ImageView mImg;
    private ImageButton mImgBtnRingCard;

    private ArrayList<Integer> ringImgList =new ArrayList<Integer>();
    private int count=0;
    private final int COUNT=3;

    TextView mTxtAdvHint=null;
    ImageView mImgStateIcon =null;
    PopupWindow mPopWaitConnection=null;

    Timer timer=new Timer();

    private IntentFilter intentFilter(){
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(BluetoothLeService.mACTION_DEVICE_READY);
        intentFilter.addAction(BluetoothLeService.mACTION_IDCARD_READ);
        intentFilter.addAction(BluetoothLeService.mACTION_IDCARD_WRITE);
        intentFilter.addAction(BluetoothLeService.mACTION_DEVICE_CONNECTING);
        intentFilter.addAction(BluetoothLeService.mACTION_DEVICE_CONNECTED);
        intentFilter.addAction(BluetoothLeService.mACTION_DEVICE_CONNECT_FAILED);
        intentFilter.addAction(BluetoothLeService.mACTION_DEVICE_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.mACTION_BLUETOOTH_BUSY);
        intentFilter.addAction(BluetoothLeService.mACTION_BLUETOOTH_AVAILABLE);
        return intentFilter;
    }
    private BroadcastReceiver bcReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            MainActivity.state =action;
            switch (action)
            {
                case BluetoothLeService.mACTION_DEVICE_CONNECTING:{

                }
                break;

                case BluetoothLeService.mACTION_DEVICE_READY:
                {
                    mHandler.sendEmptyMessageDelayed(BLUETOOTH_ACITON,BLUETOOTH_ACTION_DELAY);
                }
                break;

                case BluetoothLeService.mACTION_DEVICE_DISCONNECTED:{

                }
                break;

                case BluetoothLeService.mACTION_BLUETOOTH_BUSY:{

                }
                break;

                    case BluetoothLeService.mACTION_BLUETOOTH_AVAILABLE:{
                    mHandler.sendEmptyMessageDelayed(BLUETOOTH_ACITON,BLUETOOTH_ACTION_DELAY);
                }
                break;

                case BluetoothLeService.mACTION_DEVICE_CONNECT_FAILED:
                {
                    mHandler.sendEmptyMessageDelayed(BLUETOOTH_ACITON,BLUETOOTH_ACTION_DELAY);
                }
                break;

                case BluetoothLeService.mACTION_IDCARD_READ:
                {
                    IDcard[] mIdCards=MainActivity.mBluetoothLeService.doGetIDcards();
                    if(mIdCards.length==0){
                        Toast.makeText(getActivity(), "没有读取到新名片", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        ArrayList<HashMap<String,Object>> listOfNewContacts=new ArrayList<HashMap<String, Object>>();
                        for (IDcard i : mIdCards) {
                            HashMap<String,Object> newContact=new HashMap<String, Object>();
                            newContact.put("Name",i.n);
//                            newContact.put("StuNum",i.s);
                            newContact.put("Number", i.p);
                            listOfNewContacts.add(newContact);
                        }
                        Intent intent1=new Intent();
                        intent.setClass(getActivity(),NewContactsActivity.class);
                        intent.putExtra("newContactsList",listOfNewContacts);
                    }
                    mHandler.sendEmptyMessageDelayed(BLUETOOTH_ACITON,BLUETOOTH_ACTION_DELAY);
                }
                break;

                case BluetoothLeService.mACTION_IDCARD_WRITE:
                {
                    mHandler.sendEmptyMessageDelayed(BLUETOOTH_ACITON,BLUETOOTH_ACTION_DELAY);
                }
                break;

                default:
                    break;
            }
            setCurrStateText(action);
        }
    };
    private Handler mHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what)
            {
                case BLUETOOTH_ACITON:
                    if(MainActivity.mBluetoothLeService.getDeviceState()==BluetoothLeService.STATE_CONNECTING) {
                        MainActivity.state=BluetoothLeService.mACTION_DEVICE_CONNECTING;
                    }
                    else if(MainActivity.mBluetoothLeService.getDeviceState()==BluetoothLeService.STATE_DISCONNECTED) {
                        MainActivity.state=BluetoothLeService.mACTION_DEVICE_DISCONNECTED;
                    }
                    else if(MainActivity.mBluetoothLeService.getDeviceState()==BluetoothLeService.STATE_CONNECTED)
                    {
                        if(MainActivity.mBluetoothLeService.isDeviceBusy()){
                            MainActivity.state=BluetoothLeService.mACTION_BLUETOOTH_BUSY;
                        }
                        else {
                            MainActivity.state=BluetoothLeService.mACTION_BLUETOOTH_AVAILABLE;
                        }
                    }
                    setCurrStateText(MainActivity.state);
                    break;
                default:
                    break;
            }
        }
    };
    private void setCurrStateText(String action){
        mTxtAdvHint=(TextView)mView.findViewById(R.id.txt_adv_hint);
        mImgStateIcon =(ImageView)mView.findViewById(R.id.img_ring_state_icon);
        switch (action)
        {
            case BluetoothLeService.mACTION_DEVICE_CONNECTING:{
                mTxtAdvHint.setText("正在连接...");
                mImgStateIcon.setBackgroundResource(R.mipmap.busy);
            }
            break;

            case BluetoothLeService.mACTION_DEVICE_READY:
            {
                mTxtAdvHint.setText("已连接");
                mImgStateIcon.setBackgroundResource(R.mipmap.done);
            }
            break;

            case BluetoothLeService.mACTION_DEVICE_DISCONNECTED:{
                mTxtAdvHint.setText("未连接");
                mImgStateIcon.setBackgroundResource(R.mipmap.disconnected);
            }
            break;

            case BluetoothLeService.mACTION_BLUETOOTH_BUSY:{
                mTxtAdvHint.setText("正在通信...");
                mImgStateIcon.setBackgroundResource(R.mipmap.busy);
            }
            break;

            case BluetoothLeService.mACTION_BLUETOOTH_AVAILABLE:{
                mTxtAdvHint.setText("连接正常");
                mImgStateIcon.setBackgroundResource(R.mipmap.idle);
            }
            break;

            case BluetoothLeService.mACTION_DEVICE_CONNECT_FAILED:
            {
                mTxtAdvHint.setText("通信失败！");
                mImgStateIcon.setBackgroundResource(R.mipmap.accident);
            }
            break;

            case BluetoothLeService.mACTION_IDCARD_READ:
            {
                mTxtAdvHint.setText("同步完成!");
                mImgStateIcon.setBackgroundResource(R.mipmap.done);
            }
            break;

            case BluetoothLeService.mACTION_IDCARD_WRITE:
            {
                mTxtAdvHint.setText("名片已写入!");
                mImgStateIcon.setBackgroundResource(R.mipmap.done);
            }
            break;
            default:
                break;
        }
    }
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment RingFragment.
     */
    public static RingFragment newInstance(String param1, String param2) {
        RingFragment fragment = new RingFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public RingFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        ringImgList.add(R.mipmap.moto360);
        ringImgList.add(R.mipmap.moto360_2);
        ringImgList.add(R.mipmap.moto360_3);

        getActivity().registerReceiver(bcReceiver, intentFilter());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mView=inflater.inflate(R.layout.fragment_ring, container, false);

        setClickListenerForEachIcon(mView);

        mImgBtnRingCard=(ImageButton)mView.findViewById(R.id.imgbtn_ring_info);
        mImgBtnRingCard.setOnClickListener(this);

        mImg=(ImageView)mView.findViewById(R.id.img_ring);
        AnimationSet fadeInOut = null;
        fadeInOut=(AnimationSet)AnimationUtils.loadAnimation(getActivity(), R.anim.fade_in_out);
        count=0;
        for(Animation a:fadeInOut.getAnimations())
        {
            a.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {

                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                    count=(count+1)%(COUNT*2);
                    if(count%2==0)
                        mImg.setImageResource(ringImgList.get(count/2));
                }
            });
        }
        mImg.startAnimation(fadeInOut);

        setCurrStateText(MainActivity.state);

        return mView;
    }

    private void setClickListenerForEachIcon(View view)
    {
        SharedPreferences sharedPref = getActivity().getSharedPreferences("quickIcon", 0);
        SharedPreferences.Editor editor = sharedPref.edit();
        if(sharedPref.getInt("iconCount", 0) == 0){                                         //若未添加过快捷入口则默认添加
            editor.putString("1", "微博");
            editor.putString("2", "人人");
            editor.putInt("iconCount", 2);
            editor.commit();
        }
        int iconCount = sharedPref.getInt("iconCount", 0);
        for(int i = 0;i < webSite.MAX_ICONS;i++)       //遍历7个icon
        {
            CircleImageView icon = (CircleImageView) view.findViewById(webSite.getImgbtn_quick(i));
            if(i < iconCount){                         //对已添加的icon设置图片、可见
                icon.setImageResource(webSite.getImageId(sharedPref.getString(i + 1 + "", null)));
                icon.setVisibility(View.VISIBLE);
                icon.setOnClickListener(this);
            }
            else{                                      //对未添加的icon设置不可见
                icon.setVisibility(View.GONE);
            }
        }
        view.findViewById(R.id.imgbtn_add).setOnClickListener(this);
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

//    @Override
//    public void onAttach(Activity activity) {
//        super.onAttach(activity);
//        try {
//            mListener = (OnFragmentInteractionListener) activity;
//        } catch (ClassCastException e) {
//            throw new ClassCastException(activity.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
//    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    @Override
    public void onClick(View v) {
        Intent intent =new Intent();
        intent.setClass(getActivity(),WebActivity.class);
        ArrayList<String> iconList = new ArrayList<String>();
        SharedPreferences sharedPref = getActivity().getSharedPreferences("quickIcon", 0);
        int iconCount = sharedPref.getInt("iconCount", 0);
        for(int i = 1; i<= iconCount; i++){
            iconList.add(i-1, sharedPref.getString(i+"", null));
        }
        switch (v.getId())
        {
            case R.id.imgbtn_quick1:
                intent.putExtra("webTitle",iconList.get(0));
                startActivity(intent);
                break;
            case R.id.imgbtn_quick2:
                intent.putExtra("webTitle",iconList.get(1));
                startActivity(intent);
                break;
            case R.id.imgbtn_quick3:
                intent.putExtra("webTitle", iconList.get(2));
                startActivity(intent);
                break;
            case R.id.imgbtn_quick4:
                intent.putExtra("webTitle", iconList.get(3));
                startActivity(intent);
                break;
            case R.id.imgbtn_quick5:
                intent.putExtra("webTitle", iconList.get(4));
                startActivity(intent);
                break;
            case R.id.imgbtn_quick6:
                intent.putExtra("webTitle", iconList.get(5));
                startActivity(intent);
                break;
            case R.id.imgbtn_quick7:
                intent.putExtra("webTitle", iconList.get(6));
                startActivity(intent);
                break;
            case R.id.imgbtn_add:
                Intent intent1 = new Intent();
                intent1.setClass(getActivity(),PlusActivity.class);
                startActivityForResult(intent1, 1);
                break;
            case R.id.imgbtn_ring_info:

                if(MainActivity.mBluetoothLeService.isReady()){
                    MainActivity.mBluetoothLeService.doReadIDcard();
                }else if(MainActivity.mBluetoothLeService.isDeviceBusy()){
                    Toast.makeText(getActivity(),"正在同步，请稍后操作",Toast.LENGTH_SHORT).show();
                }else if(!MainActivity.mBluetoothLeService.isDeviceConnected()){
                    MainActivity.mBluetoothLeService.connectDevice();
                }
                break;
            default:
                break;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(Uri uri);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(bcReceiver);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case 1:
                if(resultCode == getActivity().RESULT_OK){
                    int ifIconChange = data.getIntExtra("ifIconChange", 0);
                    if(ifIconChange == PlusActivity.ICON_CHANGED){
                        Log.d(TAG, "iconChanged!");
                        setClickListenerForEachIcon(mView);
                    }
                }
                break;
            default:
        }
    }
}
